package com.tim.app.ui.activity.record;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.application.library.log.DLOG;
import com.application.library.net.StringResponseCallback;
import com.application.library.util.TimeUtil;
import com.google.gson.Gson;
import com.tim.app.R;
import com.tim.app.RT;
import com.tim.app.record.Pcm2Wav;
import com.tim.app.record.WaveView;
import com.tim.app.record.utils.CheapWAV;
import com.tim.app.record.view.RecordUtil;
import com.tim.app.server.api.API_App;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.server.result.UploadResult;
import com.tim.app.server.util.DateUtils;
import com.tim.app.ui.activity.BaseActivity;
import com.tim.app.util.ToastUtil;

import java.io.File;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 录音页面
 */
public class RecordActivity extends BaseActivity {

    private static final String TAG = "RecordActivity";

    private ImageButton ibBack;
    private ImageButton ibSave;
    private ImageView ivAddBackgroundMusic;
    private ImageView ivCutRecord;
    private WaveView wvRecord;

    private TextView tvRecordTime;

    private RelativeLayout rlWaveContainer;

    private LinearLayout llRecordPublish;//发布
    private ImageView ivPublishRecord;

    private LinearLayout llRecordAudition;//试听

    private LinearLayout llRecord;//录音
    private ImageView ivRecord;//状态按钮
    private TextView tvRecordState;//录音状态文字

    private ImageView ivLeftTape;
    private ImageView ivRightTape;

    ObjectAnimator leftAnimator;
    ObjectAnimator rightAnimator;

    private static final int FREQUENCY = 44100;// 设置音频采样率，44100是目前的标准，但是某些设备仍然支持22050，16000，11025
    private static final int CHANNELCONGIFIGURATION = AudioFormat.CHANNEL_IN_MONO;// 设置单声道声道
    private static final int AUDIOENCODING = AudioFormat.ENCODING_PCM_16BIT;// 音频数据格式：每个样本16位
    public final static int AUDIO_SOURCE = MediaRecorder.AudioSource.MIC;// 音频获取源
    private String mFileName = System.currentTimeMillis() + "";//文件名
    private int mTimeCounter = -1;

    private int currentStatus = 0;//默认为没在录制状态；1：录制状态；2为暂停装填；3为录制结束状态

    private boolean isPause = false;//默认为非暂停操作

    private String albumId;


    /**
     * 启动设置界面的统一接口
     *
     * @param context
     */
    public static void start(Context context, String albumId) {
        Intent intent = new Intent(context, RecordActivity.class);
        intent.putExtra("albumId", albumId);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_record;
    }

    @Override
    public void initView() {
        ibBack = (ImageButton) findViewById(R.id.ibBack);

        ibSave = (ImageButton) findViewById(R.id.ibSave);
        ivAddBackgroundMusic = (ImageView) findViewById(R.id.ivAddBackgroundMusic);
        ivCutRecord = (ImageView) findViewById(R.id.ivCutRecord);
        wvRecord = (WaveView) findViewById(R.id.wvRecord);

        tvRecordTime = (TextView) findViewById(R.id.tvRecordTime);

        llRecordPublish = (LinearLayout) findViewById(R.id.llRecordPublish);
        ivPublishRecord = (ImageView) findViewById(R.id.ivPublishRecord);

        llRecordAudition = (LinearLayout) findViewById(R.id.llRecordAudition);

        llRecord = (LinearLayout) findViewById(R.id.llRecord);
        ivRecord = (ImageView) findViewById(R.id.ivRecord);
        tvRecordState = (TextView) findViewById(R.id.tvRecordState);

        ivLeftTape = (ImageView) findViewById(R.id.ivLeftTape);
        ivRightTape = (ImageView) findViewById(R.id.ivRightTape);
        rlWaveContainer = (RelativeLayout) findViewById(R.id.rlWaveContainer);

        ibBack.setOnClickListener(this);
        ibSave.setOnClickListener(this);
        ivAddBackgroundMusic.setOnClickListener(this);
        ivCutRecord.setOnClickListener(this);
        llRecordPublish.setOnClickListener(this);
        llRecordAudition.setOnClickListener(this);
        llRecord.setOnClickListener(this);

        llRecordPublish.setEnabled(false);
        ivPublishRecord.setEnabled(false);
        llRecordAudition.setEnabled(false);

        if (getIntent().hasExtra("albumId")) {
            albumId = getIntent().getStringExtra("albumId");
        }
    }

    private void initAnimator() {
        leftAnimator = ObjectAnimator.ofFloat(ivLeftTape, "rotation", 0f, 359.0f);
        LinearInterpolator lin = new LinearInterpolator();
        leftAnimator.setDuration(4000);
        leftAnimator.setInterpolator(lin);
        leftAnimator.setRepeatCount(-1);//设置动画重复次数
        leftAnimator.setRepeatMode(ValueAnimator.RESTART);//动画重复模式

        rightAnimator = ObjectAnimator.ofFloat(ivRightTape, "rotation", 0f, 359.0f);
        LinearInterpolator linRight = new LinearInterpolator();
        rightAnimator.setDuration(2000);
        rightAnimator.setInterpolator(linRight);
        rightAnimator.setRepeatCount(-1);//设置动画重复次数
        rightAnimator.setRepeatMode(ValueAnimator.RESTART);//动画重复模式
    }

    @Override
    public void initData() {
        initAnimator();
        updateRecordTime("00:00");
    }

    private int recBufSize;
    private AudioRecord audioRecord;
    private RecordUtil waveCanvas;

    /**
     * 初始化录音
     */
    private void initAudio() {
        recBufSize = AudioRecord.getMinBufferSize(FREQUENCY,
                CHANNELCONGIFIGURATION, AUDIOENCODING);//设置录音缓冲区(一般为20ms,1280)
        audioRecord = new AudioRecord(AUDIO_SOURCE,// 指定音频来源，这里为麦克风
                FREQUENCY, // 16000HZ采样频率
                CHANNELCONGIFIGURATION,// 录制通道
                AUDIO_SOURCE,// 录制编码格式
                recBufSize);
        waveCanvas = new RecordUtil();
        waveCanvas.Start(audioRecord, recBufSize, mFileName, RT.defaultRecord, new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                int mVolume = msg.arg1;
                updateWaveView(mVolume);
                return true;
            }
        }, this);
    }

    private int totalTime = 0;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ibBack:
                if (null != waveCanvas) {
                    waveCanvas.Stop();
                }
                deleteRecordFile();
                finish();
            case R.id.ibSave:
                break;
            case R.id.ivAddBackgroundMusic:
                break;
            case R.id.ivCutRecord:
                break;
            case R.id.llRecordPublish:
                createWavFile();
                uploadRecordFileAndGotoPublish();
                break;
            case R.id.llRecordAudition:
                createWavFile();
                AuditionRecordActivity.start(this, RT.defaultRecord + mFileName + ".wav", totalTime - 1);
                break;
            case R.id.llRecord:
                try {
                    if (waveCanvas == null || !waveCanvas.isRecording) {
                        currentStatus = 1;
                        mTimeCounter = 0;
                        initAudio();
                        updatePlayStateUi();
                        if (null == timer_speed) {
                            timer_speed = new Timer();
                            timer_speed.schedule(timerTask_speed, 0, 500);
                        }
                    } else {
                        //录制(暂停操作)
                        switch (currentStatus) {
                            case 0:
                                break;
                            case 1://录制过程可对其进行暂停或开始操作
                                currentStatus = 2;
                                totalTime = mTimeCounter;
                                waveCanvas.pause();
                                updatePauseStateUi();
                                break;
                            case 2:
                                currentStatus = 1;
                                mTimeCounter = totalTime;
                                waveCanvas.reStart();
                                updatePlayStateUi();
                                break;
                            case 3:
                                //TODO
                                currentStatus = 1;
                                mTimeCounter = 0;
                                initAudio();
                                updatePlayStateUi();
                                break;
                            default:
                                break;
                        }
                    }

                } catch (IllegalStateException e) {
                    Toast.makeText(RecordActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    private void createWavFile() {
        currentStatus = 2;
        totalTime = mTimeCounter;
        waveCanvas.pause();
        updatePauseStateUi();
        try {
            Pcm2Wav p2w = new Pcm2Wav();//将pcm格式转换成wav 其实就尼玛加了一个44字节的头信息
            String savePcmPath = RT.defaultRecord + mFileName + ".pcm";
            String saveWavPath = RT.defaultRecord + mFileName + ".wav";
            p2w.convertAudioFiles(savePcmPath, saveWavPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 上传录音文件并且跳到发布页面
     */
    private void uploadRecordFileAndGotoPublish() {
        showLoadingDialog();
        API_App.ins().uploadRecordData(TAG, RT.defaultRecord + mFileName + ".wav", new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                hideLoadingDialog();
                if (errCode == ResponseResult.ResultStatus.OK) {
                    UploadResult result = new Gson().fromJson(resultValue, UploadResult.class);
                    if (null != result && null != result.getRes() && null != result.getRes().getHashmap()) {
                        if (null != waveCanvas) {
                            waveCanvas.Stop();
                        }
                        deleteRecordFile();
                        String url = result.getRes().getHashmap().getImgurl();
                        String time = DateUtils.formatSecond(totalTime / 1000);
                        PublishRecordActivity.start(RecordActivity.this, url, time, albumId);
                        finish();
                    }
                } else {
                    ToastUtil.showToast("上传失败，请稍后再试!");
                }
                return false;
            }
        });
    }

    /**
     * 删除录音文件
     */
    private void deleteRecordFile() {
        File mFile1 = new File(RT.defaultRecord + mFileName + ".wav");
        File mFile2 = new File(RT.defaultRecord + mFileName + ".pcm");
        if (mFile1.exists() && mFile2.exists()) {
            mFile1.delete();
            mFile2.delete();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    }

    @Override
    protected void onPause() {
        super.onPause();

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        deleteRecordFile();
        if (null != waveCanvas) {
            waveCanvas.Stop();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != audioRecord) {
            audioRecord.stop();
        }
        if (null != waveCanvas) {
            waveCanvas.Stop();
        }
    }

    /**
     * 更新录音的时间
     *
     * @param time
     */
    public void updateRecordTime(String time) {
        tvRecordTime.setText(getString(R.string.recordTime, time));
    }

    private void updatePlayStateUi() {
        ivRecord.setSelected(true);
        tvRecordState.setText(R.string.recordNow);
        leftAnimator.start();
        rightAnimator.start();
    }

    private void updatePauseStateUi() {
        ivRecord.setSelected(false);
        tvRecordState.setText(R.string.recordPause);
        leftAnimator.cancel();
        rightAnimator.cancel();
    }

    private void updateStopStateUi() {
        ivRecord.setSelected(false);
        tvRecordState.setText("录音已结束");
        leftAnimator.cancel();
        rightAnimator.cancel();
    }

    private Timer timer_speed;

    private Handler mHandler = new Handler() {
        public void dispatchMessage(android.os.Message msg) {
            switch (msg.what) {
                case 1://时间记录
                    if (mTimeCounter == -1) {
                        updateRecordTime("00:00");
                    } else {
                        if (mTimeCounter / 1000 / 1000 >= 60) {
                            waveCanvas.Stop();
                            updateStopStateUi();
                        }
                        updateRecordTime(DateUtils.formatSecond(mTimeCounter / 1000));
                        ivPublishRecord.setEnabled(true);
                        llRecordPublish.setEnabled(true);
                        llRecordAudition.setEnabled(true);
                    }
                    break;

                default:
                    break;
            }
        }
    };

    TimerTask timerTask_speed = new TimerTask() {
        @Override
        public void run() {
            if (currentStatus == 1) {
                mTimeCounter = mTimeCounter + 500;
                mHandler.sendEmptyMessage(1);
            }
        }
    };


    /**
     * 更新声波
     *
     * @param value
     */
    public void updateWaveView(final int value) {
        if (!wvRecord.hasOver()) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    wvRecord.putValue(value);
                }
            });
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

}
